package org.dalmatian.common.excel.utils;

import static cn.hutool.core.date.DatePattern.NORM_DATE_PATTERN;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;

/**
 * 存放poi操作时可公共使用的一些方法
 */
public class ExcelCellUtil {

    /*将单元格数据转换为String*/
    public static String getCellValue(Cell cell) {
        String cellValue = null;
        if (null != cell) {
            switch (cell.getCellType()) {
                case NUMERIC:
                    // Check if the number is a date
                    if (DateUtil.isCellDateFormatted(cell)) {
                        cellValue = new SimpleDateFormat(NORM_DATE_PATTERN).format(
                            cell.getDateCellValue());
                    } else {
                        // Convert numeric to string (ensure no scientific notation)
                        cellValue = BigDecimal.valueOf(cell.getNumericCellValue()).toPlainString();
                    }
                    break;
                case STRING:
                    cellValue = cell.getStringCellValue();
                    break;
                case BOOLEAN:
                    cellValue = cell.getBooleanCellValue() + "";
                    break;
                case FORMULA:
                    cellValue = cell.getCellFormula() + "";
                    break;
                case BLANK:
                    cellValue = "";
                    break;
                case ERROR:
                    cellValue = "非法字符";
                    break;
                default:
                    cellValue = "未知类型";
                    break;
            }
        }

        // 如果 cellValue 不是 null，去除空格
        if (cellValue != null) {
            cellValue = cellValue.trim();
        } else {
            cellValue = "";
        }
        return cellValue;
    }
}
